package com.lp.article.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.article.mapper.ArticleStatMapper;
import com.lp.article.mapper.CollectsMapper;
import com.lp.article.mapper.LikesMapper;
import com.lp.model.constants.MQConstants;
import com.lp.model.constants.RedisConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;

@Slf4j
@Configuration
public class CollectListener {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ArticleStatMapper articleStatMapper;

    @Autowired
    private CollectsMapper collectsMapper;

    /**
     * 收藏消息
     * @param msg userId 和 articleId
     */
    @SneakyThrows
    @RabbitListener(queues = MQConstants.ARTICLE_COLLECT_QUEUE)
    public void articleCollectMsg(String msg) {
        log.info("MQ 消息: 收藏/取消 消息 {}", msg);
        //1.解析数据
        HashMap hashMap = objectMapper.readValue(msg, HashMap.class);
        Long userId = objectMapper.convertValue(hashMap.get("userId"), new TypeReference<Long>() {});
        Long articleId = objectMapper.convertValue(hashMap.get("articleId"), new TypeReference<Long>() {});
        //2.检查 redis 上是否有收藏数据，同时将状态更新到 mysql
        if(Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(RedisConstants.ARTICLE_COLLECT + articleId,
                RedisConstants.ARTICLE_COLLECT_VALUE + userId))) {
            //1) 存在表示: 已收藏，那么现在就要删除收藏信息(取消收藏)
            redisTemplate.opsForSet().remove(RedisConstants.ARTICLE_COLLECT + articleId,
                    RedisConstants.ARTICLE_COLLECT_VALUE + userId);
            collectsMapper.remove(articleId, userId);
            articleStatMapper.collectIncrOrDecr(articleId, -1);
            log.info("用户 {} 对文章 {} 取消收藏！", userId, articleId);
        } else {
            //2) 不存在表示: 未收藏，那么现在就要增加收藏信息(收藏)
            redisTemplate.opsForSet().add(RedisConstants.ARTICLE_COLLECT + articleId,
                    RedisConstants.ARTICLE_COLLECT_VALUE + userId);
            collectsMapper.add(articleId, userId);
            articleStatMapper.collectIncrOrDecr(articleId, +1);
            log.info("用户 {} 对文章 {} 进行收藏！", userId, articleId);
        }
        log.info("MQ 完成: 收藏数据同步到 redis 和 mysql");
    }

}
